﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Configuration;
using ZYO.资源;

namespace ZYO
{
    public static class DataFactory
    {
        private static SqlCeConnection myCeConnection = null;

        private static void InitDBConnection()
        {
            String ConnString = System.IO.Path.GetDirectoryName(
                                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\iching.sdf";
            
            //Properties.Settings.Default.ConnectionString;
            myCeConnection = new SqlCeConnection(ConnString);

            try
            {
                myCeConnection.Open();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        private static void CloseDBConnection()
        {
            myCeConnection.Close();
        }

        private static DataTable ExecuteQuery(String QueryStringFormat,
                                                params String[] QueryParameters)
        {
            DataTable dtReturn = new DataTable();

            if (null == myCeConnection || myCeConnection.State != ConnectionState.Open)
            {
                InitDBConnection();
            }

            SqlCeCommand myCommand = new SqlCeCommand();
            myCommand.CommandType = CommandType.Text;
            myCommand.CommandText = String.Format(QueryStringFormat, QueryParameters);
            myCommand.Connection = myCeConnection;

            SqlCeDataAdapter myDataAdapter = new SqlCeDataAdapter(myCommand);
            myDataAdapter.Fill(dtReturn);

            return dtReturn;
        }

        public static List<object> GetSingleRow(String tablename, String[] Columns, string Filter)
        {
            string selectColumns = string.Empty;
            foreach (string col in Columns)
            {
                if (!string.IsNullOrEmpty(selectColumns))
                {
                    selectColumns += ",";
                }
                selectColumns += col;
            }

            string queryString = String.Format("Select {0} from {1} Where {2}", selectColumns, tablename, Filter);
            DataTable dtReturn = ExecuteQuery(queryString);

            List<object> resultList = new List<object>(Columns.Length);
            foreach (string col in Columns)
            {
                DataRow firstRow = dtReturn.Rows[0]; // ignore other rows, if any
                resultList.Add(firstRow[col]);
            }

            return resultList;
        }        
    }
}
